package ph.com.gs3.formalistics.presenter.fragments.views;

import java.util.List;

import ph.com.gs3.formalistics.R;
import ph.com.gs3.formalistics.model.valueobjects.business.MessageThread;
import ph.com.gs3.formalistics.presenter.adapters.ThreadListItemViewAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class ThreadListViewFragment extends Fragment {

	public static final String TITLE = "Thread List";

	private ListView lvThreadList;
	private ThreadListItemViewAdapter threadListItemViewAdapter;

	private ThreadListViewActionListener actionListener;

	public static ThreadListViewFragment createInstance() {
		ThreadListViewFragment instance = new ThreadListViewFragment();
		return instance;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		try {
			actionListener = (ThreadListViewActionListener) activity;
		} catch (ClassCastException e) {
			throw new IllegalStateException(activity.getClass().getSimpleName()
			        + " must implement ThreadListViewActionListener");
		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_thread_list, container, false);

		threadListItemViewAdapter = new ThreadListItemViewAdapter(getActivity(), null);
		lvThreadList = (ListView) rootView.findViewById(R.id.Thread_lvThreadList);
		lvThreadList.setAdapter(threadListItemViewAdapter);

		lvThreadList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

				MessageThread messageThread = (MessageThread) threadListItemViewAdapter
				        .getItem(position);

				actionListener.onThreadClicked(messageThread);
			}

		});

		return rootView;
	}

	public void setDisplayingThreads(List<MessageThread> threads) {

		threadListItemViewAdapter.resetItems(threads);

	}

	public static interface ThreadListViewActionListener {

		public void onThreadClicked(MessageThread messageThread);

	}

}
